﻿using System;

namespace Development.Network
{
    /// <summary>
    /// 动态缓存
    /// </summary>
    public class DynamicBuffer
    {
        private byte[] m_buff;               //存放内存的数组
        private int m_dataCount;             //写入数据大小

        public DynamicBuffer(int bufferSize)
        {
            m_dataCount = 0;
            m_buff = new byte[bufferSize];
        }
        public byte[] Buffer { get { return m_buff; } }

        public int DataCount { get { return m_dataCount; } }        //当前写入字节数
        public int ReserveCount { get { return m_buff.Length - m_dataCount; } }     //获取剩余字节数

        //清除缓存
        public void Clear()
        {
            m_dataCount = 0;
        }

        //清理指定大小的数据
        public void Clear(int count)
        {
            if (count >= DataCount) //如果需要清理的数据大于现有数据大小，则全部清理
            {
                m_dataCount = 0;
            }
            else
            {
                for (int i = 0; i < DataCount - count; i++) //否则后面的数据往前移
                {
                    m_buff[i] = m_buff[count + i];
                }
                m_dataCount = DataCount - count;
            }
        }

        //设置缓存大小
        public void SetBufferSize(int size)
        {

            if (m_buff.Length < size)
            {
                byte[] tmpBuffer = new byte[size];
                Array.Copy(m_buff, 0, tmpBuffer, 0, DataCount); //复制以前的数据
                m_buff = tmpBuffer; //替换
            }
        }


        public void WriteBuffer(byte[] buffer, int offset, int count)
        {

            if (ReserveCount >= count) //缓冲区空间够，不需要申请
            {
                Array.Copy(buffer, offset, m_buff, m_dataCount, count);
                m_dataCount = m_dataCount + count;
            }
            else //缓冲区空间不够，需要申请更大的内存，并进行移位
            {
                int totalSize = m_buff.Length + count - ReserveCount; //总大小-空余大小
                byte[] tmpBuffer = new byte[totalSize];
                Array.Copy(m_buff, 0, tmpBuffer, 0, DataCount); //复制以前的数据
                Array.Copy(buffer, offset, tmpBuffer, DataCount, count); //复制新写入的数据
                m_dataCount = DataCount + count;
                m_buff = tmpBuffer; //替换
            }
        }

        /// <summary>
        /// 写入缓存
        /// </summary>
        /// <param name="buffer"></param>
        public void WriteBuffer(byte[] buffer)
        {
            WriteBuffer(buffer, 0, buffer.Length);
        }


    }
}
